package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.Contact;
import domain.DAOContact;

/**
 * Servlet implementation class SearchServlet
 */
public class SearchServlet extends ContactServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String idStr = request.getParameter("id");
		int id;
		try{
			id = Integer.parseInt(idStr);
		}catch(NumberFormatException e){
			out.write(generateResponsePage("Search result", 
						"Error : " + idStr + " is not a number."));
			out.close();
			return;
		}
		
		Contact[] res = DAOContact.searchContact(id);
		Contact c;
		if(res.length == 0){
			out.write(generateResponsePage("Search result", "Not found."));
		}else{
			String data = "<table border=\"1\">" +
						"<tr><td>ID</td><td>First name</td>" +
						"<td>Second name</td><td>Email</td></tr>";
			for(int i = 0; i < res.length; i++){
				c = res[i];
				if(c == null) continue;
				data += "<tr>" +
						"<td>" + c.getId() + "</td>" +
						"<td>" + c.getFirstName() + "</td>" +
						"<td>" + c.getSecondName() + "</td>" +
						"<td>" + c.getEmail() + "</td>" +
						"</tr>";	
			}
			data += "</table>";
			out.write(generateResponsePage("Search result", data));
		}
		
		out.close();	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}


}
